package com.onenine.app.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.event.ConnectStatusEvent;
import com.onenine.app.event.RecMessageEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.event.RefreshMessageEvent;
import com.onenine.app.listener.NotificationCountReceiver;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.SoundPlayer;
import com.onenine.app.view.ChatView;
import com.onenine.app.view.RcConnectStatusBar;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.commons.IMessage;
import com.onenine.chat.commons.ImageLoader;
import com.onenine.chat.listener.OnMenuClickListener;
import com.onenine.chat.message.MsgListAdapter;
import com.onenine.chat.model.FileItem;
import com.onenine.chat.model.LMessage;
import com.onenine.chat.model.RcExtra;
import com.onenine.chat.model.ReadBurnExtra;
import com.onenine.chat.model.ReadBurnFriendExtra;
import com.onenine.chat.rongcloud.RcImMgr;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.chat.view.AudioRecordButton;
import com.onenine.chat.view.ChatInputView;
import com.onenine.common.fileprovider.FileProvider7;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.ImageUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.NetworkUtils;
import com.onenine.common.util.SizeUtils;
import com.onenine.common.util.TimeUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.GroupNotificationMessage;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 创建时间：2018/5/29 0029 10:08
 * 创建人：fly
 * 功能描述：单聊消息页
 */
public class GroupMessageActivity extends BaseEventActivity implements View.OnTouchListener, AudioRecordButton.AudioFinishRecorderListener,
        EasyPermissions.PermissionCallbacks, SensorEventListener, OnMenuClickListener, View.OnClickListener
        , MsgListAdapter.OnMsgClickListener<LMessage>, MsgListAdapter.OnMsgLongClickListener<LMessage>, BaseQuickAdapter.RequestLoadMoreListener
        , MsgListAdapter.OnAvatarClickListener<LMessage>, MsgListAdapter.OnMsgStatusViewClickListener<LMessage> {

    private final int RC_CAMERA = 0x0002;
    private final int RC_PHOTO = 0x0003;
    private final int RC_BROWSER_PHOTO = 0x0004;
    private final int RC_GET_CAMERA = 0x0007;

    private final String[] ALBUM_PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private final String[] CAMERA_PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private ChatView mChatView;
    private RcConnectStatusBar mRcStatusBar;
    private MsgListAdapter<LMessage> mAdapter;
    private InputMethodManager mImm;
    private Window mWindow;
    private HeadsetDetectReceiver mReceiver;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    private PowerManager mPowerManager;
    private PowerManager.WakeLock mWakeLock;
    private String mTargetId;
    private String mCurrentPhotoPath;
    private int imageSendingIndex;

    public static void launchActivity(Context context, String targetId, String groupName) {
        Intent intent = new Intent(context, GroupMessageActivity.class);
        intent.putExtra("targetId", targetId);
        intent.putExtra("targetName", groupName);
        context.startActivity(intent);
    }

    /**
     * 获取通知意图
     *
     * @param context
     * @param targetId
     * @param targetName
     * @return
     */
    public static Intent getNotificationIntent(Context context, String targetId, String targetName) {
        Intent intent = new Intent(context, GroupMessageActivity.class);
        intent.putExtra("targetId", targetId);
        intent.putExtra("targetName", targetName);
        intent.putExtra("fromNotification", true);
        return intent;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initViews();
        initListeners();
        loadData(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_group_chat_message;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setRightTitleDrawable(R.drawable.ic_option_gray);
        mChatView = findViewById(R.id.chat_view);
        mChatView.initModule();
        mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mRcStatusBar = findViewById(R.id.rc_status_bar);
        mWindow = getWindow();
        initMsgAdapter();
    }

    @Override
    protected void initListeners() {
        mToolbar.setOnRightClickListener(this);
        mChatView.setOnTouchListener(this);
        mChatView.setMenuClickListener(this);
        mChatView.setRecordVoiceListener(this);
        mAdapter.setOnMsgClickListener(this);
        mAdapter.setMsgLongClickListener(this);
        mAdapter.setOnAvatarClickListener(this);
        mAdapter.setMsgStatusViewClickListener(this);
        mAdapter.setOnLoadMoreListener(this);
    }

    @Override
    protected void initData() {
        loadData(getIntent());
    }

    private void loadData(Intent intent) {
        registerProximitySensorListener();
        mReceiver = new HeadsetDetectReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mReceiver, intentFilter);
        mTargetId = intent.getStringExtra("targetId");
        mToolbar.setCenterTitle(getIntent().getStringExtra("targetName"));
        mChatView.setPrivateOrGroupExpandContent(1, mTargetId);
        checkFromNotification(intent.getBooleanExtra("fromNotification", false));
        getHistoryMessages(-1);
    }

    /**
     * 处理通栏栏消息
     *
     * @param fromNotification
     */
    private void checkFromNotification(boolean fromNotification) {
        if (mTargetId != null) {
            if (fromNotification) {
                //更新通知未处理消息计数
                NotificationCountReceiver.notifyRemoveNotification(mTargetId);
                //标记该目标信息已读
                RcImMgr.getInstance().clearMsgUnreadStatus(Conversation.ConversationType.PRIVATE, mTargetId, null);
            } else {
                //如果存在通知则移除
                if (NotificationCountReceiver.hasNotification()) {
                    NotificationCountReceiver.cancelNotificationById(mTargetId);
                }
            }
        }
    }

    private void registerProximitySensorListener() {
        try {
            mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK
                    , GroupMessageActivity.class.getSimpleName());
            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
            mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        try {
            if (audioManager.isBluetoothA2dpOn() || audioManager.isWiredHeadsetOn()) {
                return;
            }
            if (mAdapter.getMediaPlayer().isPlaying()) {
                float distance = event.values[0];
                if (distance >= mSensor.getMaximumRange()) {
                    SoundPlayer.setAudioPlayByEarPhone(0);
                    setScreenOn();
                } else {
                    SoundPlayer.setAudioPlayByEarPhone(2);
                    setScreenOff();
                }
            } else {
                if (mWakeLock != null && mWakeLock.isHeld()) {
                    mWakeLock.release();
                    mWakeLock = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setScreenOn() {
        if (mWakeLock != null) {
            mWakeLock.setReferenceCounted(false);
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    private void setScreenOff() {
        if (mWakeLock == null) {
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, GroupMessageActivity.class.getSimpleName());
        }
        mWakeLock.acquire();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onStatusViewClick(LMessage message) {
        if (!NetworkUtils.isConnected()) {
            Toasty.showNormal(R.string.rc_network_exception);
            return;
        }
        switch (message.getMessageType()) {
            case SEND_TEXT:
                mAdapter.deleteByDatetime(message);
                RcImMgr.getInstance().deleteMessage(new int[]{message.getMsgId()}, null);
                sendTextMessage(message.getText());
                break;
            case SEND_IMAGE:
                mAdapter.deleteByDatetime(message);
                RcImMgr.getInstance().deleteMessage(new int[]{message.getMsgId()}, null);
                sendImageMessage(new File(message.getMediaFilePath()), isImageBurn(message.getExtra()));
                break;
            case SEND_VOICE:
                mAdapter.deleteByDatetime(message);
                RcImMgr.getInstance().deleteMessage(new int[]{message.getMsgId()}, null);
                sendVoiceMessage(new File(message.getMediaFilePath()), (int) message.getDuration());
                break;
        }
    }

    @Override
    public void onAvatarClick(View view, LMessage message) {
        if (!TextUtils.equals(RcUser.getInstance().getUserId(), message.getSentUserId())) {
            UserDetailActivity.launchActivity(this, message.getSentUserId());
        }
    }

    @Override
    public void onMessageClick(View view, LMessage message) {
        if (message.getMessageType() == IMessage.MessageType.RECEIVE_IMAGE
                || message.getMessageType() == IMessage.MessageType.SEND_IMAGE) {
            BrowserImageActivity.launchActivityForResult(GroupMessageActivity.this, view, message.getMsgId()
                    , message.getMediaFilePath(), isImageBurn(message.getExtra()), RC_BROWSER_PHOTO);
        }
    }


    @Override
    public void onFinished(float seconds, String filePath) {
        if (!NetworkUtils.isConnected()) {
            Toasty.showNormal(R.string.rc_network_exception);
            return;
        }
        sendVoiceMessage(new File(filePath), (int) seconds);
    }

    @Override
    public boolean onSendTextMessage(CharSequence input) {
        if (input.length() == 0) {
            return false;
        }
        if (TextUtils.isEmpty(mTargetId)) {
            return false;
        }
        if (!NetworkUtils.isConnected()) {
            Toasty.showNormal(R.string.rc_network_exception);
            return false;
        }
        sendTextMessage(input.toString());
        return true;
    }


    @Override
    public void onSendFiles(List<FileItem> list) {
    }

    @Override
    public boolean onSendVoiceMessage() {
        return true;
    }

    @Override
    public boolean onExpandOption(int position) {
        switch (position) {
            case 0:
                if (EasyPermissions.hasPermissions(this, ALBUM_PERMISSIONS)) {
                    launchAlbum();
                } else {
                    EasyPermissions.requestPermissions(this
                            , getString(R.string.permission_extra_storage_hint), RC_PHOTO, ALBUM_PERMISSIONS);
                }
                break;
            case 1:
                if (EasyPermissions.hasPermissions(this, CAMERA_PERMISSIONS)) {
                    openCamera();
                } else {
                    EasyPermissions.requestPermissions(this, getString(R.string.permission_camera_hint)
                            , RC_CAMERA, CAMERA_PERMISSIONS);
                }
                break;
        }
        return true;
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            String filename = TimeUtils.getNowMills() + ".png";
            File file = new File(Environment.getExternalStorageDirectory(), filename);
            mCurrentPhotoPath = file.getAbsolutePath();
            Uri fileUri = FileProvider7.getUriForFile(this, file);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(takePictureIntent, RC_GET_CAMERA);
        } else {
            Toasty.showNormal(R.string.can_not_open_camera);
        }
    }


    @Override
    public boolean switchToCameraMode() {
        return true;
    }

    @Override
    public void onMessageLongClick(View view, LMessage message) {
    }

    @Override
    public boolean switchToEmojiMode() {
        scrollToBottom();
        return true;
    }

    @Override
    public boolean switchToExpandMode() {
        return true;
    }

    @Override
    public void onLoadMoreRequested() {
        loadNextPage();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_right_title) {
            GroupOptionActivity.launchActivity(this, mTargetId);
        }
    }

    private class HeadsetDetectReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.hasExtra("state")) {
                    int state = intent.getIntExtra("state", 0);
                    SoundPlayer.setAudioPlayByEarPhone(state);
                }
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == RC_PHOTO && perms.size() == ALBUM_PERMISSIONS.length) {
            launchAlbum();
        } else if (requestCode == RC_CAMERA && perms.size() == CAMERA_PERMISSIONS.length) {
            openCamera();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == RC_PHOTO) {
            Toasty.showNormal(R.string.permission_extra_storage_hint);
        } else if (requestCode == RC_CAMERA) {
            Toasty.showNormal(R.string.permission_camera_hint);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RC_PHOTO) {
                compressImages(Matisse.obtainPathResult(data), Matisse.obtainBurnReadSelected(data));
            } else if (requestCode == RC_GET_CAMERA) {
                compressImages(Arrays.asList(mCurrentPhotoPath), false);
            } else if (requestCode == RC_BROWSER_PHOTO) {
                if (data != null && data.getBooleanExtra(BrowserImageActivity.BURN, false)) {
                    int msgId = data.getIntExtra(BrowserImageActivity.MSG_ID, -1);
                    if (msgId > -1) {
                        //删除阅后即焚信息
                        mAdapter.deleteById(msgId);
                        RcImMgr.getInstance().deleteMessage(new int[]{msgId}, new RongIMClient.ResultCallback<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {
                                Logger.e("删除阅后即焚的消息：" + aBoolean);
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                            }
                        });
                    }
                }
            }
        }
    }

    /**
     * 初始化适配器
     */
    private void initMsgAdapter() {
        final int avatarSize = getResources().getDimensionPixelSize(R.dimen.aurora_width_msg_avatar);
        ImageLoader imageLoader = new ImageLoader() {
            @Override
            public void loadAvatarImage(ImageView avatarImageView, String string) {
                GlideUtils.loadCircleAvatar(ApUtils.getApp(), avatarImageView
                        , CHelper.getOssThumbImageUrl(string, avatarSize));
            }

            @Override
            public void loadImage(ImageView imageView, String string, Object extra) {
                GlideUtils.loadChatFitImage(imageView, string, isImageBurn(extra));
            }

            @Override
            public void loadVideo(ImageView imageCover, String uri) {
                long interval = 5000 * 1000;
                Glide.with(GroupMessageActivity.this)
                        .asBitmap()
                        .load(uri)
                        // Resize image view by change override size.
                        .apply(new RequestOptions().frame(interval).override(200, 400))
                        .into(imageCover);
            }
        };
        MsgListAdapter.MyMultiItemEntity holdersConfig = new MsgListAdapter.MyMultiItemEntity();
        mAdapter = new MsgListAdapter<>(holdersConfig, imageLoader);
        mAdapter.closeLoadAnimation();
        mChatView.setAdapter(mAdapter);
        mAdapter.setStackFromEndPageSize(AppConfig.PAGE_SIZE);
        scrollToBottom();
    }

    private void loadNextPage() {
        List<LMessage> msgList = mAdapter.getMessageList();
        if (msgList.isEmpty()) {
            getHistoryMessages(-1);
        } else {
            LMessage lastMessage = msgList.get(msgList.size() - 1);
            if (lastMessage.getMsgId() != 0) {
                getHistoryMessages(lastMessage.getMsgId());
            }
        }
    }

    /**
     * 滑动至底部
     */
    private void scrollToBottom() {
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                mAdapter.getLayoutManager().scrollToPosition(0);
                return false;
            }
        });
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ChatInputView chatInputView = mChatView.getChatInputView();
                if (chatInputView.getMenuState() == View.VISIBLE) {
                    chatInputView.dismissMenuLayout();
                }
                try {
                    View v = getCurrentFocus();
                    if (mImm != null && v != null) {
                        mImm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        view.clearFocus();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_UP:
                view.performClick();
                break;
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RecMessageEvent event) {
        if (event.message != null && event.message.getConversationType() == Conversation.ConversationType.GROUP
                && TextUtils.equals(event.message.getTargetId(), mTargetId)) {
            LMessage locMessage = new LMessage(event.message);
            mAdapter.addToStart(locMessage, !mChatView.canScrollFirstVertically());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshMessageEvent event) {
        if (event.newMessage != null) {
            if (event.delMsgIds != null && event.delMsgIds.length > 0) {
                mAdapter.deleteByIds(event.delMsgIds);
            }
            if (TextUtils.equals(mTargetId, event.newMessage.getTargetId())) {
                LMessage locMessage = new LMessage(event.newMessage);
                mAdapter.addToStart(locMessage, !mChatView.canScrollFirstVertically());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ConnectStatusEvent event) {
        mRcStatusBar.setVisible(event.isShow())
                .showStatusMsg(event.getMsg());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(final GroupNotificationMessage groupMessage) {
        switch (groupMessage.getOperation()) {
            case GroupNotificationMessage.GROUP_OPERATION_DISMISS:
                //群组解散
                finish();
                break;
            case GroupNotificationMessage.GROUP_OPERATION_RENAME:
                //群组重命名
                LMessage lMessage = new LMessage(groupMessage.getExtra()
                        , Conversation.ConversationType.GROUP, IMessage.MessageType.EVENT);
                lMessage.setMessageStatus(Message.SentStatus.SENT);
                lMessage.setText(groupMessage.getMessage());
                mAdapter.addToStart(lMessage, !mChatView.canScrollFirstVertically());
                mToolbar.setCenterTitle(groupMessage.getData());
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(final InformationNotificationMessage message) {
        if (TextUtils.equals(message.getExtra(), GroupNotificationMessage.GROUP_OPERATION_ADD)
                || TextUtils.equals(message.getExtra(), GroupNotificationMessage.GROUP_OPERATION_KICKED)) {
            //拉人或踢人刷新当前小灰条
            LMessage lMessage = new LMessage(message.getMessage()
                    , Conversation.ConversationType.GROUP, IMessage.MessageType.EVENT);
            lMessage.setMessageStatus(Message.SentStatus.SENT);
            mAdapter.addToStart(lMessage, !mChatView.canScrollFirstVertically());
        } else {
            //修改群名称
            mToolbar.setCenterTitle(message.getExtra());
        }
    }

    private void launchAlbum() {
        int size = AppConfig.SCREEN_WIDTH / 3 - SizeUtils.dp2px(10);
        Matisse.from(GroupMessageActivity.this)
                .choose(MimeType.ofImage())//照片视频全部显示
                .maxSelectable(9)//最大选择数量为9
                .gridExpectedSize(size)//图片显示表格的大小getResources()
                .showSingleMediaType(true)//只显示一种媒体类型，此处只会显示图片，过滤了视频
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题  暗色主题 R.style.Matisse_Dracula
                .imageEngine(new GlideEngine())//加载方式
                .showImageBurn(true)
                .forResult(RC_PHOTO);//请求码
    }

    /**
     * 生成本地消息列表
     *
     * @param messages
     * @return
     */
    private List<LMessage> genLocalMessages(final List<Message> messages) {
        final List<LMessage> locMessages = new ArrayList<>();
        final int messageCount = messages.size();
        for (int i = 0; i < messageCount; i++) {
            locMessages.add(new LMessage(messages.get(i)));
        }
        return locMessages;
    }

    /**
     * 获取本地历史消息
     *
     * @param messageId
     */
    private void getHistoryMessages(final int messageId) {
        RcImMgr.getInstance().getHistoryMessages(Conversation.ConversationType.GROUP, mTargetId
                , messageId, new RongIMClient.ResultCallback<List<Message>>() {
                    @Override
                    public void onSuccess(final List<Message> messages) {
                        if (messages.isEmpty()) {
                            mAdapter.loadMoreEnd(true);
                            return;
                        }
                        List<LMessage> lMessages = genLocalMessages(messages);
                        mAdapter.addToEnd(lMessages, mAdapter.getItemCount() == 0);
                        if (messages.size() == AppConfig.PAGE_SIZE) {
                            mAdapter.loadMoreComplete();
                        } else {
                            mAdapter.loadMoreEnd(true);
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        mAdapter.loadMoreFail();
                    }
                });
    }

    /**
     * 压缩图片在100kb左右
     * 发送出去
     *
     * @param images
     */
    private void compressImages(final List<String> images, final boolean isBurnSelected) {
        imageSendingIndex = 0;
        Luban.with(this)
                .load(images).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        sendImageMessageDelay(file, isBurnSelected, imageSendingIndex++);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    /**
     * 延时一次发送过多图片消息，避免融云
     * 报发送消息频率过高， 1 秒钟最多只允许发送 5 条消息
     *
     * @param file
     * @param isBurnSelected
     */
    private void sendImageMessageDelay(final File file, final boolean isBurnSelected, final int index) {
        mChatView.postDelayed(new Runnable() {
            @Override
            public void run() {
                sendImageMessage(file, isBurnSelected);
            }
        }, index * 500);
    }

    /**
     * 更新头部消息发送状态
     *
     * @param lMessage
     * @param messageStatus
     */
    private void updateStartMessageStatus(LMessage lMessage, Message.SentStatus messageStatus) {
        lMessage.setMessageStatus(messageStatus);
        if (lMessage.getMessageType() == IMessage.MessageType.SEND_IMAGE) {
            int position = mAdapter.findMessagePositionByFilePath(lMessage.getMediaFilePath());
            if (position >= 0) {
                mAdapter.notifyItemChanged(position);
            }
        } else {
            mAdapter.notifyItemChanged(0);
        }
    }


    /**
     * 发送文本消息
     *
     * @param input
     */
    private void sendTextMessage(final String input) {
        final LMessage lMessage = new LMessage(input, Conversation.ConversationType.GROUP, IMessage.MessageType.SEND_TEXT);
        lMessage.setMessageStatus(Message.SentStatus.SENDING);
        mAdapter.addToStart(lMessage, true);
        RcImMgr.getInstance().sendTextMessage(Conversation.ConversationType.GROUP, mTargetId
                , input, new RcImMgr.OnMessageListener() {
                    @Override
                    public void onSuccess(Message message) {
                        switch (message.getSentStatus()) {
                            case FAILED:
                                //发送失败
                                updateStartMessageStatus(lMessage, Message.SentStatus.FAILED);
                                break;
                            case SENT:
                                //发送成功
                                updateStartMessageStatus(lMessage, Message.SentStatus.SENT);
                                break;
                        }
                    }

                    @Override
                    public void onProgress(Message message) {
                        if (message.getSentStatus() == Message.SentStatus.SENDING) {
                            updateStartMessageStatus(lMessage, Message.SentStatus.SENDING);
                        }
                    }

                    @Override
                    public void onFailure(RongIMClient.ErrorCode errorCode) {
                        if (errorCode == RongIMClient.ErrorCode.NOT_IN_GROUP) {
                            //已不在群组了
                            Toasty.showNormal(R.string.not_in_group);
                            finish();
                            return;
                        }
                        updateStartMessageStatus(lMessage, Message.SentStatus.FAILED);
                    }

                });
    }

    /**
     * 发送语音消息
     *
     * @param voiceFile
     * @param duration
     */
    private void sendVoiceMessage(File voiceFile, int duration) {
        final LMessage lMessage = new LMessage(null, Conversation.ConversationType.GROUP, IMessage.MessageType.SEND_VOICE);
        lMessage.setMediaFilePath(voiceFile.getPath());
        lMessage.setDuration(duration);
        mAdapter.addToStart(lMessage, true);
        RcImMgr.getInstance().sendVoiceMessage(Conversation.ConversationType.GROUP, mTargetId, voiceFile.getPath(), duration, new RcImMgr.OnMessageListener() {
            @Override
            public void onSuccess(Message message) {
                switch (message.getSentStatus()) {
                    case FAILED:
                        //发送失败
                        updateStartMessageStatus(lMessage, Message.SentStatus.FAILED);
                        break;
                    case SENT:
                        //发送成功
                        updateStartMessageStatus(lMessage, Message.SentStatus.SENT);
                        break;
                }
            }

            @Override
            public void onProgress(Message message) {
                if (message.getSentStatus() == Message.SentStatus.SENDING) {
                    updateStartMessageStatus(lMessage, Message.SentStatus.SENDING);
                }
            }

            @Override
            public void onFailure(RongIMClient.ErrorCode errorCode) {
                if (errorCode == RongIMClient.ErrorCode.NOT_IN_GROUP) {
                    //已不在群组了
                    Toasty.showNormal(R.string.not_in_group);
                    finish();
                    return;
                }
                updateStartMessageStatus(lMessage, Message.SentStatus.FAILED);
            }
        });
    }

    /**
     * 发送图片消息
     *
     * @param imageFile
     */
    private void sendImageMessage(final File imageFile, boolean isBurnSelected) {
        if (!NetworkUtils.isConnected()) {
            Toasty.showNormal(R.string.rc_network_exception);
            return;
        }
        //生成缩略图
        final String thumbPath = ImageUtils.saveImageThumb(imageFile.toString(), 4);
        //新增一条当前图片消息
        final LMessage lMessage = new LMessage(thumbPath, Conversation.ConversationType.GROUP, IMessage.MessageType.SEND_IMAGE);
        lMessage.setMediaFilePath(imageFile.getPath());
        lMessage.setMessageStatus(Message.SentStatus.SENDING);
        RcExtra extra = null;
        if (isBurnSelected) {
            extra = new ReadBurnExtra(isBurnSelected);
        }
        final RcExtra finalExtra = extra;
        lMessage.setExtra(extra);
        //发送图片
        RcImMgr.getInstance().sendImageMessage(Conversation.ConversationType.GROUP, mTargetId, thumbPath, imageFile.getPath()
                , finalExtra, new RcImMgr.OnMessageListener() {
                    @Override
                    public void onSuccess(Message message) {
                        switch (message.getSentStatus()) {
                            case FAILED:
                                //发送失败
                                updateStartMessageStatus(lMessage, Message.SentStatus.FAILED);
                                break;
                            case SENT:
                                //发送成功
                                lMessage.setMediaFilePath(((ImageMessage) message
                                        .getContent()).getRemoteUri().toString());
                                updateStartMessageStatus(lMessage, Message.SentStatus.SENT);
                                break;
                        }
                    }

                    @Override
                    public void onProgress(Message message) {
                        if (message.getSentStatus() == Message.SentStatus.SENDING) {
                            lMessage.setText(((ImageMessage) message
                                    .getContent()).getThumUri().toString());
                            mAdapter.addToStart(lMessage, true);
                            updateStartMessageStatus(lMessage, Message.SentStatus.SENDING);
                        }
                    }

                    @Override
                    public void onFailure(RongIMClient.ErrorCode errorCode) {
                        if (errorCode == RongIMClient.ErrorCode.NOT_IN_GROUP) {
                            //已不在群组了
                            Toasty.showNormal(R.string.not_in_group);
                            finish();
                            return;
                        }
                        updateStartMessageStatus(lMessage, Message.SentStatus.FAILED);
                    }
                });

    }

    /**
     * 是否附带阅后即焚标志
     *
     * @param burnObject
     * @return
     */
    private boolean isImageBurn(Object burnObject) {
        boolean isBurn = false;
        if (burnObject instanceof ReadBurnExtra) {
            isBurn = ((ReadBurnExtra) burnObject).isBurn();
        } else if (burnObject instanceof ReadBurnFriendExtra) {
            isBurn = ((ReadBurnFriendExtra) burnObject).isBurn();
        }
        return isBurn;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().post(new RefreshEvent(DataType.REFRESH_CLEAR_UNREAD_COUNT));
        mAdapter.pauseVoice();
        unregisterReceiver(mReceiver);
        mSensorManager.unregisterListener(this, mSensor);
        mChatView.clearAudioStageListener();
        mAdapter.clearListeners();
        super.onDestroy();
    }

}
